<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { AreaItem } from '@/apis/model/resolve'
import { Message } from '@arco-design/web-vue'
import { omit } from 'lodash-es'
// import {
//   addApiResolveRegionApi,
//   updateApiResolveRegionApi,
// } from '@/apis/modules/resolve/area'
import { addCdnClusterApi, updateCdnClusterApi } from '@/apis/modules/cdn.ts'
// import { getApiResolveDomainsApi } from '@/apis/modules/resolve/domain'
interface IProp {
  record?: AreaItem
}
const props = withDefaults(defineProps<IProp>(), {})
const emit = defineEmits(['reload'])
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
const formState = reactive({
  name: '',
  remark: '',
})

const rules: Record<string, FieldRule[] | FieldRule> = {
  name: [{ required: true, message: '请输入区域名称' }],
}
const title = computed(() => (props.record?.id ? '编辑区域' : '新建区域'))

async function createArea() {
  const data = { ...omit(formState, ['cname']) }
  await addCdnClusterApi(data).then(() => {
    Message.success('操作成功')
    visible.value = false
    emit('reload')
  })
}
async function updateArea() {
  const data = {
    ...formState,
  }
  await updateCdnClusterApi(data).then(() => {
    Message.success('操作成功')
    visible.value = false
    emit('reload')
  })
}
async function handleSubmit() {
  const error = await formRef.value?.validate()

  if (error)
    return false
  return props.record?.id ? updateArea() : createArea()
}

function handleClose() {
  formRef.value?.resetFields()
}

async function handleOpen() {
  if (props.record) {
    formState.name = props.record.name!
    formState.remark = props.record.remark!
  }
}
onMounted(() => {
  handleOpen()
})
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    :title="title"
    :width="480"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-close="handleClose"
    ok-text="保存"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :rules="rules"
      :model="formState"
    >
      <a-form-item
        label="区域名称"
        field="name"
        asterisk-position="end"
      >
        <a-input
          v-model="formState.name"
          :max-length="32"
          show-word-limit
          placeholder="请输入区域名称"
        />
      </a-form-item>
      <a-form-item
        label="备注"
        field="remark"
        asterisk-position="end"
      >
        <a-textarea
          v-model="formState.remark"
          :max-length="200"
          show-word-limit
          :auto-size="{ maxRows: 5, minRows: 5 }"
          placeholder="请输入备注"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>

<style lang="less" scoped></style>
